/**
 * @IntIdentifier.java  COPYRIGHT xiaojian
 * 
 * Created on 2018年3月15日 上午10:53:17
 */
package xj.toolkit.util;

import java.io.Serializable;

import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;

import com.google.common.base.Preconditions;

/**
 * @author <a href="mailto:cxj2000@gmail.com">xiaojian.cao</a>
 *
 */
public class IntIdentifier implements Identifier<Integer>, Serializable {

	private static final long serialVersionUID = 6525608176472021457L;
	
	private int value = RandomUtils.nextInt(0, Integer.MAX_VALUE);
	
	public IntIdentifier(){}
	
	public IntIdentifier(int value) {
		this.value = value;
	}

	@Override
	public Integer getValue() {
		return value;
	}

	@Override
	public void setVaule(Integer t) {
		this.value = t;
	}

	@Override
	public String valueAsString() {
		return String.valueOf(value);
	}

	@Override
	public int valueAsInt() {
		return value;
	}
	
	@Override
	public byte[] valueAsByte() {
		return DefaultNumberCodecs.getBigEndianNumberCodec().int2Bytes(value, 4);
	}

	@Override
	public IntIdentifier fromSrting(String id) {
		Preconditions.checkArgument(StringUtils.isNoneBlank(id));
		this.value = Integer.parseInt(id);
		return this;
	}

	@Override
	public IntIdentifier fromInt(int id) {
		this.value = id;
		return this;
	}

	/**
	 * int的长度就是4个字节。
	 */
	@Override
	public int length() {
		return 4;
	}

	@Override
	public boolean equals(Object other) {
		Preconditions.checkArgument(other != null);

		if (!(other instanceof IntIdentifier)) {
			return false;
		}

		IntIdentifier ii = (IntIdentifier) other;
		if (ii.getValue() == null && getValue() == null) {
			return true;
		}
		
		if (ii.getValue() != null && getValue() == null) {
			return false;
		}
		
		if (ii.getValue() == null && getValue() != null) {
			return true;
		}
		return ii.getValue().intValue() == getValue().intValue();
	}
	
	@Override
	public int hashCode() {
		return this.value;
	}

	@Override
	public IntIdentifier fromByte(byte[] bArray) {
		Preconditions.checkArgument(bArray != null && bArray.length > 0);

		this.value = DefaultNumberCodecs.getBigEndianNumberCodec().bytes2Int(bArray, bArray.length);
		return this;
	}
	
	public String toString() {
		return "IntIdentifier[value=" + this.value + "]";
	}

}
